package cn.buildoncloud.labor.workermanapplet.business.modules.services.impl;

import cn.buildoncloud.labor.workermanapplet.business.modules.services.UserService;
import cn.buildoncloud.labor.workermanapplet.common.Constant;
import cn.buildoncloud.labor.workermanapplet.common.base.service.BaseServiceImpl;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.entity.Record;
import org.nutz.dao.sql.Sql;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class UserServiceImpl extends BaseServiceImpl<Map> implements UserService {

    public UserServiceImpl(Dao dao) {
        super(dao);
    }

    @Override
    public Map<String, Object> getUserByOpenId(String userId) {

        StringBuilder sb = new StringBuilder(" SELECT CONCAT(su_r.userId,'') id, su.username, s_un.`name` unit_name,  GROUP_CONCAT(distinct  sr.`name` SEPARATOR ',') role_name, CONCAT(su.images_id,'') images_id, su.phone, su.email ");
        sb.append(" FROM sys_user_role su_r ");
        sb.append(" LEFT JOIN applet_user_sys_user au_su ON au_su.sys_user_id = su_r.userId ");
        sb.append(" LEFT JOIN applet_user au ON au.id = au_su.applet_user_id ");
        sb.append(" LEFT JOIN sys_user su ON su_r.userId = su.id ");
        sb.append(" LEFT JOIN sys_role sr ON su_r.roleId = sr.id ");
        sb.append(" LEFT JOIN sys_unit s_un ON su.unitid = s_un.id ");
        sb.append(" WHERE su.id = @userId ");
        sb.append(" GROUP BY su_r.userId ");

        Sql sql = Sqls.create(sb.toString());
        sql.setParam("userId", userId);
        List<Record> result = this.list(sql);
        if (result.size() > 0){
            return result.get(0);
        }
        return null;
    }

    @Override
    public void updateProfilePhoto(Long id, String urlId) {
        this.update("sys_user", Chain.make("images_id", urlId), Cnd.where("id", " = ", id));
    }

    @Override
    public void updateName(Long id, String name) {
        this.update("sys_user", Chain.make("username", name), Cnd.where("id", " = ", id));
    }

    /**
     * 查询用户角色code列表
     *
     * @param uid
     * @return
     */
    @Override
    public List<String> getRoleCodeList(String uid) {
        List<String> roleCodeIds = new ArrayList<>();
        List<Record> list = dao().query("sys_user_role", Cnd.where("userId", "=", uid));
        list.stream().forEach(item -> {
            Long roleId = item.getLong("roleId");
            if (roleId != null) {
                Record role = dao().fetch("sys_role", Cnd.where("id", "=", roleId));
                if (role != null) {
                    roleCodeIds.add(role.getString("code"));
                }
            }
        });
        return roleCodeIds;
    }

    /**
     * 获取当前用户管理范围内项目ID集合
     * 总公司 全部未删除项目ID，分公司所属项目 项目经理管理项目
     *
     * @return
     */
    @Override
    public List<String> getScopeProjectIds(String uid) {

        Set<String> projectIds = new HashSet<>();
        List<String> roleCodeList = getRoleCodeList(uid);
        Cnd cnd = Cnd.where("delFlag", "=", false);
        if (roleCodeList.contains(Constant.ROLE_HEAD_OFFICE_ADMIN)) {//总公司
            List<Record> projects = dao().query("bi_project", cnd);
            projects.stream().forEach(item -> {
                projectIds.add(item.getLong("id") + "");
            });

        } else if (roleCodeList.contains(Constant.ROLE_BRANCH_ADMIN)) {//分公司
            Record user = dao().fetch("sys_user", Cnd.where("id", "=", uid));
            cnd.and("unit_id", "=", user.getLong("unitid"));
            List<Record> projects = dao().query("bi_project", cnd);
            projects.stream().forEach(item -> {
                projectIds.add(item.getLong("id") + "");
            });

        }
        if (roleCodeList.contains(Constant.ROLE_PROJECT_ADMIN)) {//项目管理员
            Record role = dao().fetch("sys_role", Cnd.where("code", "=", Constant.ROLE_PROJECT_ADMIN));
            List<Record> userRoles = dao().query("sys_user_role", Cnd.where("userId", "=", uid)
                    .and("roleId", "=", role.getLong("id")));
            userRoles.stream().forEach(item -> {
                String id = item.getLong("projectId") + "";
                if (id != null) {
                    projectIds.add(item.getLong("projectId") + "");
                }
            });
        }
        if (roleCodeList.contains(Constant.ROLE_PROJECT_COMMISSIONER)) {//作业所负责人
            Record role = dao().fetch("sys_role", Cnd.where("code", "=", Constant.ROLE_PROJECT_COMMISSIONER));
            List<Record> userRoles = dao().query("sys_user_role", Cnd.where("userId", "=", uid)
                    .and("roleId", "=", role.getLong("id")));
            userRoles.stream().forEach(item -> {
                String id = item.getLong("projectId") + "";
                if (id != null) {
                    projectIds.add(item.getLong("projectId") + "");
                }
            });
        }
        List<String> list = new ArrayList<>();
        list.addAll(projectIds);
        return list;
    }

    @Override
    public String getUserIdByOpenId(String openId) {
        if (openId == null) {
            return null;
        }
        Sql sql = Sqls.create("SELECT CONCAT(t3.id,'') id FROM `applet_user` t1 LEFT JOIN applet_user_sys_user t2 ON t2.applet_user_id = t1.id LEFT JOIN sys_user t3 ON t3.id = t2.sys_user_id WHERE t1.openid = @openId");
        sql.setParam("openId", openId);
        List<Record> list = this.list(sql);
        if (list != null && list.size() > 0) {
            return (String) list.get(0).getString("id");
        }
        return null;
    }

}
